package com.example.application9;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.Manifest;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.application9.bean.SuggestBean;
import com.example.application9.bean.WeatherBean;
import com.google.gson.Gson;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationManagerOptions;
import com.tencent.map.geolocation.TencentLocationRequest;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, TencentLocationListener {


    //和风天气 免费的api接口
    // 例子 https://api.seniverse.com/v3/weather/now.json?key=SpldNm3TTTyv1EquF&location=北京&language=zh-Hans&unit=c"
    private static final String API_WEATHER_URL = "https://api.seniverse.com/v3/weather/now.json";
    private static final String API_SUGGEST_URL = "https://api.seniverse.com/v3/life/suggestion.json";

    //注册心知天气开发者https://www.seniverse.com/
    private String key = "SqjHJtXUVUh63SkDb";// 实验三.3环节记录的私钥
    private String locationkey = "JCOBZ-T4SEL-GGBPG-EWOHK-IXBN7-QCB3C";// 百度地图sdk私钥

    /**
     * 请输入该省份的城市
     */
    private EditText mCityEdit;
    /**
     * 查询
     */
    private Button mSearch;
    /**
     * 城市的天气
     */
    private TextView mCityWeather;
    private TextView mWeather;
    private ImageView mlocation;

    String city;//接收输入的城市收用的字符串
    private LinearLayout mWeatherInfo;
    private TextView mSuggestion;
    private ProgressBar progress;
    private TencentLocationManager instance;
    private String TAG = "MainActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 百度地图设置key和用户隐私
        TencentLocationManagerOptions.setKey(locationkey);
        TencentLocationManager.setUserAgreePrivacy(true);
        initView();
        initData();  //IndicesType初始化

    }

    private void initData(){
        instance = TencentLocationManager.getInstance(this);
        instance.setDeviceID(this,"test");
    }

    private void initView() {
        mCityEdit = (EditText) findViewById(R.id.city_edit);
        mSearch = (Button) findViewById(R.id.search);
        mlocation = (ImageView) findViewById(R.id.iv_location);
        mSearch.setOnClickListener(this);
        mlocation.setOnClickListener(this);
        mCityWeather = (TextView) findViewById(R.id.city_weather);
        mWeather = (TextView) findViewById(R.id.weather);
        mWeatherInfo = (LinearLayout) findViewById(R.id.weather_info);
        mSuggestion = (TextView) findViewById(R.id.suggestion);
        progress = (ProgressBar) findViewById(R.id.progress);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.search) {
            city = mCityEdit.getText().toString().trim();
            queryWeatherByCity(city);
            progress.setVisibility(View.VISIBLE);
        }else if (v.getId() == R.id.iv_location){
            // 检查是否已经授予了ACCESS_FINE_LOCATION权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                // 如果没有权限，则请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        1);
            } else {
                // 已经有权限，可以进行定位相关的操作
                startLocation();
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户同意了权限请求
                startLocation();
            } else {
                // 用户拒绝了权限请求
                Toast.makeText(this,"无法获取定位",Toast.LENGTH_LONG).show();
            }
        }
    }
    private void startLocation(){
        progress.setVisibility(View.VISIBLE);
        TencentLocationRequest request = TencentLocationRequest.create();
        request.setGpsFirst(true);
        instance.requestSingleFreshLocation(request, this, Looper.getMainLooper());
    }
    private void queryWeatherByCity(String location){
        OkHttpClient client = new OkHttpClient();
        /**
         * 实况天气
         */
        HttpUrl url = HttpUrl.parse(API_WEATHER_URL).newBuilder()
                .addQueryParameter("key", key)
                .addQueryParameter("location", location)
                .addQueryParameter("language", "zh-Hans")
                .addQueryParameter("unit", "c")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d(TAG, "Request failed: " + e.getMessage());
                progress.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    Log.d(TAG, "onResponse: "+responseData);
                    Gson gson = new Gson();//创建Gson解析对象
                    //反序例化，将json数据转化为实体类对象的成员变量值
                    WeatherBean weatherBean = gson.fromJson(responseData, WeatherBean.class);
                    Message message = new Message();
                    message.what = 2;
                    message.obj = weatherBean;
                    myHandler.sendMessage(message);
                } else {
                    Log.d(TAG, "Unexpected code " + response);
                    progress.setVisibility(View.GONE);
                }
            }
        });
        /**
         * 建议
         */
        OkHttpClient client1 = new OkHttpClient();

        HttpUrl suggestUrl = HttpUrl.parse(API_SUGGEST_URL).newBuilder()
                .addQueryParameter("key", key)
                .addQueryParameter("location", location)
                .addQueryParameter("language", "zh-Hans")
                .addQueryParameter("days", "5")
                .build();
        Request suggestRequest = new Request.Builder()
                .url(suggestUrl)
                .build();

        client1.newCall(suggestRequest).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d(TAG, "Request failed: " + e.getMessage());
                progress.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    Log.d(TAG, "onResponse: "+responseData);
                    Gson gson = new Gson();//创建Gson解析对象
                    //反序例化，将json数据转化为实体类对象的成员变量值
                    SuggestBean suggestBean = gson.fromJson(responseData, SuggestBean.class);
                    Message message = new Message();
                    message.what = 1;
                    message.obj = suggestBean;
                    myHandler.sendMessage(message);
                } else {
                    Log.d(TAG, "Unexpected code " + response);
                    progress.setVisibility(View.GONE);
                }
            }
        });
    }


    Handler myHandler = new Handler(new Handler.Callback() {
        @SuppressLint("SetTextI18n")
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            progress.setVisibility(View.GONE);
            switch (msg.what){
                case 2:
                    mCityWeather.setVisibility(View.VISIBLE);
                    mWeatherInfo.setVisibility(View.VISIBLE);
                    WeatherBean weatherBean =(WeatherBean)msg.obj;
                    WeatherBean.Result result1 = weatherBean.getResults().get(0);
                    WeatherBean.Now now = result1.getNow();
                    mCityWeather.setText(mCityEdit.getText().toString() + "的天气");
                    mWeather.setText("当前温度：" + now.getTemperature() +", 天气："+now.getText());
                    break;
                case 1:
                    mCityWeather.setVisibility(View.VISIBLE);
                    mWeatherInfo.setVisibility(View.VISIBLE);
                    SuggestBean suggestBean = (SuggestBean)msg.obj;
                    SuggestBean.Result result = suggestBean.getResults().get(0);
                    SuggestBean.Suggestion suggestion = result.getSuggestion().get(0);
                    mSuggestion.setText(
                            "预报日期："+suggestion.getDate()+"\n"+
                                    "空调："+suggestion.getAc().getBrief()+"\n" +
                                    "建议："+suggestion.getAc().getDetails()+"\n" +
                                    "空气质量："+suggestion.getAirPollution().getBrief()+"\n" +
                                    "建议："+suggestion.getAirPollution().getDetails()+"\n" +
                                    "感冒："+suggestion.getAllergy().getBrief()+"\n" +
                                    "建议："+suggestion.getAllergy().getDetails()+"\n" +
                                    "饮酒："+suggestion.getBeer().getBrief()+"\n" +
                                    "建议："+suggestion.getBeer().getDetails()+"\n"+
                                    "划船："+suggestion.getBoating().getBrief()+"\n" +
                                    "建议："+suggestion.getBoating().getDetails()+"\n");

                    break;
            }
            return true;
        }
    });

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        Log.d(TAG, "onLocationChanged: ");
        mCityEdit.setText(tencentLocation.getCity());
        progress.setVisibility(View.GONE);
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {
        Log.d(TAG, "onStatusUpdate: ");
        progress.setVisibility(View.GONE);
    }
}
